﻿using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using System.Web;
using UtilsORM;
using UtilsORM.MySqlData;
using Models.Common;
using UtilsORM.MySqlData;
using UtilsBase;
using UtilsCache;

namespace GatewayServer.Common
{
    public class BaseMagerController : Controller
    {
        //
        // GET: /Base/
        protected MagerLoginInfo LoginUserInfo = new MagerLoginInfo();

        ////复写父类的该方法。执行控制器中的方法之前先执行该方法。从而实现过滤的功能。
        //public override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    //string _controllerName = filterContext.RouteData.Values["controller"].ToString();
        //    //string _actionName = filterContext.RouteData.Values["action"].ToString();
        //    //object _routeName = filterContext.RouteData.DataTokens["area"];
        //    base.OnActionExecuting(filterContext);  //调用父类的该方法。
        //    if (Request.Cookies["CurrentUser"].ToString() != null)
        //    {
        //        //filterContext.HttpContext.Response.Redirect("/QRCodeRecruitment/Index");  //这种跳转方式，会继续向下执行Controller的方法并返回IActionResult。
        //    }
        //    else
        //    {
        //        //这种跳转方式直接返回一个IActionResult，不会继续向下执行，而是直接跳转。速度快。
        //        filterContext.Result = Redirect("/Login/index"); ///ManageUATClient
        //    }
        //}
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            LoginUserInfo = BaseUserLoginInfo(filterContext);
            if (LoginUserInfo == null)
            {
                filterContext.Result = Redirect("/MagerLogin/LogOut");
                return;
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

        }

        public MagerLoginInfo BaseUserLoginInfo(ActionExecutingContext context)
        {

            if (HttpContext.GetCookiesValue("Data_LoginInfo") != null)//判断是否已经登录
            {
                try
                {
                    // LoginUserInfo.IsLogin = true;
                    string logintoken = HttpUtility.UrlDecode(HttpContext.GetCookiesValue("Data_LoginInfo").ToString());

                    string token = logintoken.Split('|')[0];
                    string Emp_Guid = logintoken.Split('|')[1];
                    string GetTimeStamp = logintoken.Split('|')[2];
                    DateTime gettime = UtilsDateTime.getStampToDateTime(long.Parse(GetTimeStamp));

                    string checktoken = UtilsDecrypt.MD5Encrypt(UtilAppsettingCache.getSetting("MyWebSite:CookiesKey") + Emp_Guid + GetTimeStamp);
                    if (token != checktoken || gettime < DateTime.Now.AddDays(-1))
                    {//核查有效性
                        return null;
                    }


                    //判断如果存在，就读缓存，不存在或者有更新就读更新
                    MagerLoginInfo LoginInfoRedisValue = UtilMemoryCacheHelper.StringGet<MagerLoginInfo>("bs_logintoken_" + Emp_Guid.ToUpper());
                    if (LoginInfoRedisValue != null)
                    {
                        return LoginInfoRedisValue;
                    }
                    LoginUserInfo = new MagerLoginInfo();
                    LoginUserInfo.user_guid = Emp_Guid;


                    string sql = "select * from bs_manage_user_role inner join bs_manage_role on r_guid=ur_r_guid  where ur_cu_guid=@emp_guid";
                    DataTable dt = new MySqlYihongIot().Db.Ado.GetDataTable(sql, new { emp_guid = Emp_Guid });// DBUtility.MySqlHelper.GetDataTable(sql, spterempguidrole);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {//读取角色

                        LoginUserInfo.r_guid = dt.Rows[i]["r_guid"].ToString();
                    }
                    dt.Dispose();


                    sql = @"select * from  bs_client_user where cu_guid=@emp_guid  ";

                    dt = new MySqlYihongIot().Db.Ado.GetDataTable(sql, new { emp_guid = Emp_Guid }); //DBUtility.MySqlHelper.GetDataTable(sql, spterempguid);

                    if (dt.Rows.Count > 0)
                    {

                        LoginUserInfo.user_Name = dt.Rows[0]["cu_name"].ToString();
                        LoginUserInfo.userCompanyGuid = dt.Rows[0]["cu_c_guid"].ToString();
                        LoginUserInfo.user_guid = dt.Rows[0]["cu_guid"].ToString();
                        if (dt.Rows[0]["cu_power_type"].ToString() == "super")
                        {
                            LoginUserInfo.isSupperAdmin = true;//超管
                        }
                    }
                    dt.Dispose();

                    sql = "select * from bs_manage_role_power where rp_cu_guid=@RP_Emp_Guid";
                    //  SqlParameter[] spterrpempguid = { new SqlParameter("@RP_Emp_Guid", Emp_Guid) };
                    //string empRolepower = "";
                    //List<UserLoginPower> userLoginPowers = new List<UserLoginPower>();
                    //UserLoginPower userLoginPower = new UserLoginPower();
                    //dt = new MySqlYihongIot().Db.Ado.GetDataTable(sql, new { RP_Emp_Guid = Emp_Guid });// DBUtility.MySqlHelper.GetDataTable(sql, spterrpempguid);
                    //for (int i = 0; i < dt.Rows.Count; i++)
                    //{//读取管理的公司和项目
                    //    empRolepower += "," + dt.Rows[i]["rp_com_guid"].ToString() + "_" + dt.Rows[i]["rp_project_guid"].ToString() + "_" + dt.Rows[i]["rp_dep_guid"].ToString();
                    //    userLoginPower = new UserLoginPower();
                    //    userLoginPower.powerId = dt.Rows[i]["rp_com_guid"].ToString();
                    //    userLoginPower.type = 2;
                    //    userLoginPowers.Add(userLoginPower);

                    //    userLoginPower = new UserLoginPower();
                    //    userLoginPower.powerId = dt.Rows[i]["rp_project_guid"].ToString();
                    //    userLoginPower.type = 4;
                    //    userLoginPowers.Add(userLoginPower);


                    //    userLoginPower = new UserLoginPower();
                    //    userLoginPower.powerId = dt.Rows[i]["rp_dep_guid"].ToString();
                    //    userLoginPower.type = 100;
                    //    userLoginPowers.Add(userLoginPower);

                    //}
                    //empRolepower = empRolepower.Trim(',');
                    //LoginUserInfo.userLoginPowers = userLoginPowers;

                    ////读取大登录页选租的租户，管理租户ID
                    //string loginCompanyGuid = UtilMemoryCacheHelper.StringGet("company_" + Emp_Guid.ToUpper());
                    //if (!string.IsNullOrEmpty(loginCompanyGuid))
                    //{
                    //    LoginUserInfo.userCompanyGuid = (loginCompanyGuid);
                    //}
                    //else
                    //{
                    //    LoginUserInfo.userCompanyGuid = LoginUserInfo.userCompanyGuid;
                    //}


                    //bs_client pM_Company = new MySqlYihongIot().Db.Queryable<bs_client>().Where(c => c.c_guid == LoginUserInfo.userCompanyGuid.ToString()).First();// && c.CPY_PowerType == "Operator" && c.CPY_Status == 1
                    // if (pM_Company != null)
                    // {

                    //     LoginUserInfo.isOperatorAdmin = true;
                    //     if (LoginUserInfo.userCompanyGuid != LoginUserInfo.userCompanyGuid)
                    //     {
                    //         //是否运营商,如果是运营商管理 租户则 true，如果自己管自己则false
                    //         LoginUserInfo.hasOperatorPower = true;
                    //     }
                    // }


                    // if (LoginUserInfo.isSupperAdmin == true && LoginUserInfo.userCompanyGuid != LoginUserInfo.userCompanyGuid)
                    // {//如果非租户内的超管 则false
                    //     LoginUserInfo.isSupperAdmin = false;
                    // }

                    //写入redis
                    UtilMemoryCacheHelper.StringSet("bs_logintoken_" + Emp_Guid.ToUpper(), LoginUserInfo);
                }
                catch (Exception ex)
                {
                    Response.Redirect("/MagerLogin/LogOut");
                }
            }
            else
            {
                return null;
            }



            return LoginUserInfo;
        }

    }
}
